import { serializeParams } from "@masx200/search-hash-params-router";
import { createconfig } from "@masx200/webpack-react-vue-spa-awesome-config";
import fsextra from "fs-extra";
import htmlminifierterser from "html-minifier-terser";
import { createRequire } from "module";
import path, { join } from "path";
import { PuppeteerPrerenderPlugin } from "puppeteer-prerender-plugin";
import webpack from "webpack";
import markdownconfig from "./markdown.config.js";
import "../prerender/btoa-atob.cjs";
import minifyopts from "../prerender/minifyopts.js";
const require = createRequire(import.meta.url);
const { DefinePlugin, EnvironmentPlugin } = webpack;
var __dirname = path.resolve(process.cwd());
const pagepath = path.resolve(__dirname, "./temp/page");

export default async (env, argv) => {
    await fsextra.ensureDir(pagepath);
    const config = createconfig(env, argv);
    const webpackconfig = config;
    webpackconfig.output.publicPath = "/";
    if ("production" === process.env.NODE_ENV) {
        webpackconfig.entry = [
            require.resolve("@masx200/ie11-usual-polyfills"),
            join(__dirname, "src", "polyfill.js"),
            ...webpackconfig.entry,
        ];
    }
    config.plugins = [
        ...config.plugins,
        new DefinePlugin({
            __VUE_OPTIONS_API__: true,
            __VUE_PROD_DEVTOOLS__: true,
        }),
        new EnvironmentPlugin({ PRERENDER: false }),
        new DefinePlugin({
            "process.env.browser": true,
        }),
    ];
    config.resolve.alias = { ...config.resolve.alias, "~": __dirname };
    const babelrule = config.module.rules.find(
        (rule) => rule.loader === require.resolve("babel-loader")
    );
    babelrule.test = /\.(js|mjs|jsx|ts|tsx|cjs)$/;
    babelrule.include = [__dirname];
    if (process.env.PRERENDER) {
        const { createprerenderplugin, getmenulist, onlistenstart } =
            await import("../bin/prerender.js");
        if (process.env.PRERENDER && process.env.NODE_ENV !== "development") {
            const { minify } = htmlminifierterser;
            const opts = minifyopts;
            const menulist = await getmenulist();
            config.plugins = [
                ...config.plugins,
                new PuppeteerPrerenderPlugin({
                    async postProcess(result) {
                        result.html = await minify(result.html, opts);
                    },
                    puppeteerOptions: {
                        args: ["--no-sandbox", "--disable-setuid-sandbox"],
                        defaultViewport: {
                            width: 500,
                            height: 1080,
                        },
                    },
                    discoverNewRoutes: false,
                    entryDir: path.resolve(__dirname, "dist"),
                    enabled:
                        process.env.PRERENDER &&
                        process.env.NODE_ENV !== "development",
                    renderAfterEvent: "__RENDERED__",
                    outputDir: "dist",
                    // renderAfterTime: 5000,
                    maxConcurrent: 5,
                    routes: [
                        ...menulist.map(
                            (u) => "/" + serializeParams({ md: u })
                        ),
                        "/", // Renders to dist/index.html
                    ],
                }),
            ];
        }
        if (process.env.NODE_ENV !== "development" && process.env.PRERENDER) {
            config.plugins = [...config.plugins, createprerenderplugin()];
        }
        if (
            process.env.NODE_ENV == "development" &&
            process.env.PRERENDER &&
            process.env.WEBPACK_SERVE === "true"
        ) {
            config.devServer.onListening = () => {
                onlistenstart({
                    root: __dirname,
                    baseurl: markdownconfig.baseurl,
                });
            };
        }
    }

    if (
        process.env.NODE_ENV == "development" &&
        process.env.WEBPACK_SERVE === "true"
    ) {
        config.experiments = {
            ...config.experiments,
            lazyCompilation: { entries: false, imports: true },
        };
    }
    webpackconfig.context = __dirname;
    config.resolve = { ...config.resolve, roots: [__dirname] };
    config.module.rules = [
        ...config.module.rules,
        {
            test: /\.html$/i,
            loader: "html-loader",
        },
    ];
    // console.log(process.env.PRERENDER)
    return webpackconfig;
};
